package com.guangyuan.network.dao.jdbc.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.guangyuan.network.constants.SqlType;
import com.guangyuan.network.dao.interfaces.DefaultDao;
import com.guangyuan.network.datasource.pool.util.ConnectionUtil;

public class DefaultDaoImpl implements DefaultDao{

	protected static Logger logger = Logger.getLogger(DefaultDaoImpl.class);
	
	@Override
	public Object executeSql(Connection conn, String sql, Object[] parameters,
			SqlType type) {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			pstmt = ConnectionUtil.getStatement(conn, sql, type);
			
			if(null != parameters) {
				for(int i = 0;i < parameters.length; i ++) {
					pstmt.setObject(i + 1, parameters[i]);
				}
			}
			
			if(pstmt.execute()) {
				if(SqlType.INSERT.equals(type)) {
					if(pstmt.getGeneratedKeys().next()) {
						System.out.println("test");
						return pstmt.getGeneratedKeys().getInt(1);
					}
				}
				rs = pstmt.getResultSet();
			} else {
				if(SqlType.INSERT.equals(type)) {
					rs = pstmt.getGeneratedKeys();
					System.out.println("test");
					if(rs.next()) {
						System.out.println("test");
						return rs.getInt(1);
					}
				}
				System.out.println("update");
				return pstmt.getUpdateCount();
			}
			
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		
		return rs;
	}

}
